package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.LoginDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired(required = false)
    LoginService loginService;
    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<LoginDO> wrapper = new QueryWrapper<>();
        wrapper.eq("id",username);
        LoginDO loginDO = loginService.getOne(wrapper);
        if (loginDO==null){
            //认证失败
            throw new UsernameNotFoundException("用户名不存在！");
        }
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(loginDO.getRolename());
        return new User(loginDO.getId(),new BCryptPasswordEncoder().encode(loginDO.getPassword()),auths);
    }
}
